//
//  CHVideoPlayerViewController.swift
//  bridging_js
//
//  Created by cyptt on 2021/8/30.
//

import UIKit
import AVKit
class CHVideoPlayerViewController: UIViewController {

    private var videoName = "";
    //播放源队列
    private var videoQueue:Array<URL> = []
    //播放控制
    private var avPalyer = AVPlayer()
    //访问资源信息等
    private var playItem:AVPlayerItem!
    //控制视频内容在ui上的显示
    var playerLayer = AVPlayerLayer(player: AVPlayer())
    //用于监听播放进度
    private var playTimeObserver:Any?

    //UI控件
    private var videoView = UIView()
    private let progressView = UISlider()
    private let timeLabel  = UILabel()
    private let playButton = UIButton()
    //底部控制栏
    private let navigationView = UIView()
    
    //存储当前视频的最长时间
    private var maxTime = "--:--"
    //标志当前视频在播放队列中的位置
    private var currentIndex = 0
    //标志进度是否被拖动
    private var isSliding = 0
    //标志用户的触摸状态
    private var isTouching  = false
    
    //标志手指在屏幕上开始移动的坐标
    private var startPoint:CGPoint = CGPoint(x: 0, y: 0)
  
    //标志手指上次触摸位置的位置
    private var lastPoint:CGPoint = CGPoint(x: 0, y: 0)
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        setUI()

    }


    init(videoName:String,url:URL){
        self.init()
        self.videoName = videoName
        self.videoQueue.append(url)
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("")
    }

    init(videoName:String,urls:[URL],preferred:Int) {
        self.init()
        self.videoName = videoName
        self.videoQueue = urls
        if self.videoQueue.count <= 0 {
            return
        }
        //设置默认播放源
        if self.videoQueue.count <= 0{return}
        switchPlayBackSource(url: videoQueue[preferred])
        
    }
    
    
    private func switchPlayBackSource(url:URL){
        playItem = AVPlayerItem(url: url)
        avPalyer.replaceCurrentItem(with: playItem)
        playItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
        playerLayer = AVPlayerLayer(player: avPalyer)
        playerLayer.frame = videoView.bounds
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        if videoView.layer.sublayers != nil && videoView.layer.sublayers!.count > 0 {
            videoView.layer.sublayers!.removeAll()
        }
        videoView.layer.addSublayer(playerLayer)
        
        avPlayerPlay()
        
    }

    
    //播放
    public func avPlayerPlay(){
        
        avPalyer.play()
        playButton.isSelected = true
    }
    
    //暂停
    
    public func avPlayerPause(){
        avPalyer.pause()
        playButton.isSelected = false
    }
    
    //监听进度
    private func monitoringProgress(timescal:CMTimeScale){
        weak var WeakSelf = self
        playTimeObserver = self.avPalyer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: timescal/1000), queue: DispatchQueue.global(), using: { (time) in
            
            DispatchQueue.main.async {
                guard let weakSelf = WeakSelf else {return}
            }
        })
    }
    
    private func setUI(){
        videoView.frame = self.view.bounds
        videoView.translatesAutoresizingMaskIntoConstraints = false
        videoView.backgroundColor = UIColor.black
        self.view.addSubview(videoView)
        let videoViewH:[NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[View]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["View":videoView])
        let videoViewV:[NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[View]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["View":videoView])
        
        self.view.addConstraints(videoViewH)
        self.view.addConstraints(videoViewV)
        
        //自定义导航栏
        navigationView.translatesAutoresizingMaskIntoConstraints = false
        navigationView.backgroundColor  = UIColor.init(displayP3Red: 0.1, green: 0.1, blue: 0.1, alpha: 0.25)
  
        let navigationViewH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[View]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["View":navigationView])
        let navigationViewV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[View(80)]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["View":navigationView])
        self.view.addConstraints(navigationViewH)
        self.view.addConstraints(navigationViewV)
        
        playerLayer.frame = videoView.frame
        
    }
    
    
}
